package com.spirit.mypopup;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.ListPopupWindow;
import androidx.core.content.ContextCompat;

import com.spirit.mypopup.adapter.QAdapter;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * author : fang.zhang
 * e-mail : initzf@126.com
 * date   : 2019-10-20
 * desc   :
 */
public class MyMenuFilterView extends LinearLayout {
    private static final String TAG = "MyMenuFilterView";
    private int mItemWidth;

    private Map<String, ListPopupWindow> windowMap;

    private OnMyItemClickListener clickListener;

    public MyMenuFilterView(Context context) {
        this(context, null);
    }

    public MyMenuFilterView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyMenuFilterView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOrientation(LinearLayout.HORIZONTAL);

        windowMap = new LinkedHashMap<>();
    }

    private int pxToDp(int px) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, px, getResources().getDisplayMetrics());
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(widthMeasureSpec, MeasureSpec.makeMeasureSpec(pxToDp(55), MeasureSpec.EXACTLY));
    }


    private Map<String, List<String>> map;

    public void setData(Map<String, List<String>> map) {
        this.map = map;

        Log.i(TAG, "setData: ");

        draw();
    }


    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        Log.i(TAG, "onFinishInflate: ");
    }

    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        super.onWindowFocusChanged(hasWindowFocus);
        Log.i(TAG, "onWindowFocusChanged: " + hasWindowFocus);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        Log.i(TAG, "onSizeChanged: ");


    }


    private void draw() {
        mItemWidth = getMeasuredWidth() / map.size();

        setWeightSum(map.size());

        Set<Map.Entry<String, List<String>>> entries = map.entrySet();

        for (Map.Entry<String, List<String>> entry : entries) {

            String key = entry.getKey();
            List<String> value = entry.getValue();

            createView(key, value);
        }
    }


    private ListPopupWindow popWindow;

    private void createView(final String title, List<String> strings) {

        final QAdapter qAdapter = new QAdapter(getContext(), strings);

        ViewGroup view = (ViewGroup) LayoutInflater.from(getContext()).inflate(R.layout.item_layout, null);
        int tempId;
        view.setId(tempId = View.generateViewId());

        Log.i(TAG, "createView: " + mItemWidth + "---->" + title);

        LinearLayout.LayoutParams params =
                new LayoutParams(mItemWidth,
                        LayoutParams.MATCH_PARENT);
        params.gravity = Gravity.CENTER;
        view.setLayoutParams(params);

        final TextView viewById = view.findViewById(R.id.tvTitle);

        viewById.setText(title);

        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow = windowMap.get(title);
                if (popWindow == null) {
                    popWindow = createPopWindow(viewById, qAdapter);
                    windowMap.put(title, popWindow);
                }

                Log.i(TAG, "onClick: " + (popWindow.isShowing()));

                if (!popWindow.isShowing()) {
                    popWindow.show();

                    Activity activity = (Activity) getContext();
                    Window window = activity.getWindow();
                    WindowManager.LayoutParams attributes = window.getAttributes();
                    attributes.alpha = 0.7f;
                    window.setAttributes(attributes);

                } else {
                    popWindow.dismiss();
                }

                if (popWindow.isShowing()) {

                    popWindow.getListView()
                            .setBackgroundColor(ContextCompat.getColor(getContext(), R.color.white));

                    popWindow.getListView().setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
                }

            }
        });

        addView(view);
    }

    public void setClickListener(OnMyItemClickListener clickListener) {
        this.clickListener = clickListener;
    }

    private ListPopupWindow createPopWindow(final TextView textView, final QAdapter adapter) {
        final ListPopupWindow listPopupWindow =
                new ListPopupWindow(getContext(), null, R.attr.listPopupWindowStyle);


        listPopupWindow.setHeight(pxToDp(200));
        listPopupWindow.setAdapter(adapter);

        listPopupWindow.setAnimationStyle(R.style.QMUI_Animation_PopDownMenu_Center);
        listPopupWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.transparent)));


        //listPopupWindow.setAnchorView((View) textView.getParent());
        listPopupWindow.setAnchorView(this);

        listPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                Log.i(TAG, "onDismiss: ");

                Activity activity = (Activity) getContext();
                Window window = activity.getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                attributes.alpha = 1f;
                window.setAttributes(attributes);
            }
        });


        listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Log.i(TAG, "onItemClick: " + adapter.getItem(position));

                if(adapter.getSelectPosi()==position){
                    adapter.setPosition(Adapter.NO_SELECTION);
                    textView.setTextColor(ContextCompat.getColor(getContext(), R.color.black));
                    textView.setText("不选中");
                }else{
                    adapter.setPosition(position);
                    textView.setTextColor(ContextCompat.getColor(getContext(), R.color.colorAccent));
                    textView.setText(adapter.getItem(position));
                }


                if (clickListener != null) {
                    clickListener.OnMyItemClick(adapter.getItem(position));
                }

                listPopupWindow.dismiss();
            }
        });
        return listPopupWindow;
    }
}
